package com.example.comon.service;


import com.example.comon.domain.Constants;
import com.example.comon.domain.LoginUser;
import com.example.comon.exception.ServiceException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * token(令牌)处理服务 主要是它的生产、获取、校验
 *
 * 该版本的token 不能自动刷新 也不能强制退出
 * 没有使用redis 或者mysql持久化保存token
 * 为了结构简单先这样处理
 */
@Component
public class TokenService {

    // 令牌自定义标识
    private String header= "Authorization";

    // 令牌秘钥
    private String secret= "vwx8aopefghijw15klqrst2uvb9cdwxmnyz";

    // 令牌有效期（默认30分钟）
    private int expireTime = 30;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    @Autowired
    private RedisCache redisCache;



   /* public static void main(String[] args) {
        String token="eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6eyJ1c2VySWQiOjAsImxvZ2luVGltZSI6MTcxNTMyODQ1Mzk1MywiZXhwaXJlVGltZSI6MTcxNTMzMDI1Mzk1M319.hMwrnW6aDsXszVNSP1g5w4v61p5dyDpE7WWZmDSgBse5SRyjJGMUyHfe8bosq3DjJ7m5_W4QrAki4VUjiL_ZPA";
        Claims claims =  Jwts.parser()
                .setSigningKey("vwx8aopefghijw15klqrst2uvb9cdwxmnyz")
                .parseClaimsJws(token)
                .getBody();
        LoginUser loginUser = new LoginUser();
        BeanMap beanMap =  BeanMap.create(loginUser);
        Map<String, Object> map=  (Map)claims.get(Constants.LOGIN_USER_KEY);
        System.out.println(loginUser.getExpireTime());
    }*/

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (token !=null && !token.isEmpty()) {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            LoginUser user = redisCache.getCacheObject(userKey);
            return user;
        }
       return null;
    }


    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        String token = UUID.randomUUID().toString();
        loginUser.setToken(token);
        refreshToken(loginUser);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= 0) {
            throw new ServiceException("登录已到期，请重新登录");
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);

        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    private String getTokenKey(String uuid)
    {
        return Constants.LOGIN_USER_KEY + uuid;
    }



    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (token !=null && !token.isEmpty() && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }


}
